﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using AtletIS.Shared.Helpers;

namespace AtletIS.Shared.Forms.Signups
{
    public partial class frmSignups : Form
    {

        #region Form

        // Constructor
        public frmSignups()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.AtletIS64;
        }

        // Form Load
        private void frmSignups_Load(object sender, EventArgs e)
        {
            lblTitle.Text = Globals.ActiveCompetition.Name;

            // Get clubs, countries
            DatabaseHelper.FillClubsActive(this.aDbDataSet.Clubs);
            this.taCountries.Fill(this.aDbDataSet.Countries);

            if (Globals.ActiveCompetition.ClubsCountries == true)
            {
                countriesComboBox.Enabled = false;
                DatabaseHelper.FillCompetitorsByClubId(this.aDbDataSet.Competitors, clubsComboBox.SelectedValue.ToString());
            }
            else
            {
                clubsComboBox.Enabled = false;
                DatabaseHelper.FillCompetitorsByCountryId(this.aDbDataSet.Competitors, countriesComboBox.SelectedValue.ToString());
            }

            // DatabaseHelper.FillDisciplineListByCompetitionId(this.aDbDataSet.DisciplineList, Globals.ActiveCompetition.ID);
            
            DisciplineListHelper.FillTreeView(this.tvDisciplines);
            if (tvDisciplines.Nodes.Count > 0)
            {
                tvDisciplines.SelectedNode = tvDisciplines.Nodes[0];
                tvDisciplines_AfterSelect(null, null);
            }
            
            this.ReloadPerformancesGrid();
        }

        #endregion

        #region TreeView, DataGridView

        // DisciplineList tree view selection changed
        private void tvDisciplines_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.ReloadPerformancesGrid();
        }

        // Obnovi grid prihlasenych pretekarov
        private void ReloadPerformancesGrid()
        {
            if (tvDisciplines.SelectedNode != null)
            {
                int disciplineListId = Convert.ToInt32(tvDisciplines.SelectedNode.Name);

                if (this.chkClubs.Checked)
                {
                    string filterClubId = ((DataRowView)this.cbClubsFilter.SelectedItem)["ID"].ToString();
                    DatabaseHelper.FillPerformancesByDisciplineListIdClubId(this.aDbDataSet.Performances, disciplineListId, filterClubId);
                }
                else if (this.chkCountries.Checked)
                {
                    string filterCountryId = ((DataRowView)this.cbCountriesFilter.SelectedItem)["ID"].ToString();
                    DatabaseHelper.FillPerformancesByDisciplineListIdCountryId(this.aDbDataSet.Performances, disciplineListId, filterCountryId);
                }
                else
                {
                    DatabaseHelper.FillPerformancesByDisciplineListId(this.aDbDataSet.Performances, disciplineListId);
                }
            }
        }

        //// DataGridSelection changed
        //private void disciplineListDataGridView_SelectionChanged(object sender, EventArgs e)
        //{
        //    this.ReloadPerformancesGrid();
        //}

        #endregion

        #region Clubs, countries combo box events

        // Get competitors for selected club
        private void clubsComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            DatabaseHelper.FillCompetitorsByClubId(this.aDbDataSet.Competitors, clubsComboBox.SelectedValue.ToString());
        }

        // Get competitors for selected country
        private void countriesComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            DatabaseHelper.FillCompetitorsByCountryId(this.aDbDataSet.Competitors, countriesComboBox.SelectedValue.ToString());
        }

        #endregion

        #region ToolBar events

        // Otvori rychle prihlasky
        private void tsbQuickSignup_Click(object sender, EventArgs e)
        {
            frmSignupsQuick myQuickSignupForm = new frmSignupsQuick();
            myQuickSignupForm.ShowDialog();
        }

        // Otvori import prihlasok z Excelu
        private void tsbImport_Click(object sender, EventArgs e)
        {
            frmSignupsImport mySignupsImport = new frmSignupsImport();
            mySignupsImport.ShowDialog();
        }

        // Export pretekov do Excelu
        private void tsbExport_Click(object sender, EventArgs e)
        {
            Helpers.SignupsExportHelper.ExportCompetition(Globals.ActiveCompetition.ID);
        }

        // Otvori vyhladanie v prihlaskach
        private void tsbFind_Click(object sender, EventArgs e)
        {
            frmSignupsFind myFindForm = new frmSignupsFind();
            myFindForm.ShowDialog();
        }

        // Otvori priradenie st.cisel
        private void tsbAddStNum_Click(object sender, EventArgs e)
        {
            frmSignupsAddStNum myFrmSignupsAddStNum = new frmSignupsAddStNum();
            myFrmSignupsAddStNum.ShowDialog();
        }

        // Vygeneruje subor s poctami prihl. pretekarov
        private void tsmiCounts_Click(object sender, EventArgs e)
        {
            Helpers.SignupsListHelper.HtmlSignupCountList(Globals.ActiveCompetition);
        }

        // Vygeneruje subor so zoznamom prihlasenych podla disciplin
        private void tsmiSignupsDisciplines_Click(object sender, EventArgs e)
        {
            Helpers.SignupsListHelper.HtmlSignupListForDisciplines(Globals.ActiveCompetition);
        }

        // Vygeneruje subor so zoznamom prihlasenych podla klubov
        private void tsmiSignupsClubs_Click(object sender, EventArgs e)
        {
            Helpers.SignupsListHelper.HtmlSignupListForClubs(Globals.ActiveCompetition);
        }

        // Vygeneruje subor so zoznamom prihlasenych podla krajin
        private void tsbSignupsCountries_Click(object sender, EventArgs e)
        {
            Helpers.SignupsListHelper.HtmlSignupListForCountries(Globals.ActiveCompetition);
        }

        // Close
        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region Entries filtering events

        private void chkClubs_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkClubs.Checked & this.chkCountries.Checked)
                this.chkCountries.Checked = false;

            this.cbClubsFilter.Enabled = this.chkClubs.Checked;

            this.ReloadPerformancesGrid();
        }

        private void chkCountries_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkClubs.Checked & this.chkCountries.Checked)
                this.chkClubs.Checked = false;

            this.cbCountriesFilter.Enabled = this.chkCountries.Checked;

            this.ReloadPerformancesGrid();
        }

        private void cbClubsFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbClubsFilter.SelectedItem == null)
                return;

            this.ReloadPerformancesGrid();
        }

        private void cbCountriesFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCountriesFilter.SelectedItem == null)
                return;

            this.ReloadPerformancesGrid();
        }

        private void chkCancelAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dgvr in dgvPerformances.Rows)
            {
                dgvr.Cells["chkDel"].Value = chkCancelAll.Checked;
            }
        }

        #endregion

        #region Add, delete events

        // Create entry
        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (tvDisciplines.SelectedNode == null)
                    return;
                
                foreach (DataGridViewRow dgvr in dgvCompetitors.Rows)
                {
                    if (Convert.ToBoolean(dgvr.Cells["chk"].Value))
                    {
                        var drvCompetitor = dgvr.DataBoundItem as DataRowView;

                        Data.aDbDataSet.PerformancesRow drPerformance = aDbDataSet.Performances.NewPerformancesRow();

                        drPerformance.DisciplineListId = Convert.ToInt32(tvDisciplines.SelectedNode.Name);
                        drPerformance.CompetitorId = Convert.ToInt32(drvCompetitor["ID"]);
                        drPerformance.FirstName = drvCompetitor["FirstName"].ToString();
                        drPerformance.Surname = drvCompetitor["Surname"].ToString();
                        drPerformance.Birthdate = Convert.ToDateTime(drvCompetitor["Birthdate"]);
                        drPerformance.Club = drvCompetitor["ClubId"].ToString();
                        drPerformance.CountryId = drvCompetitor["CountryId"].ToString();
                        drPerformance.SMS = string.Empty;
                        drPerformance.StartNumber = 0;
                        drPerformance.Lane = 0;
                        drPerformance.Code = 0;
                        drPerformance.SB = 0;   // Lokalne prihlaseni pretekari nemaju SB, PB zo statistiky
                        drPerformance.PB = 0;
                        drPerformance.Result = 0;
                        drPerformance.ResultQuality = string.Empty;
                        drPerformance.AdvResult = 0;
                        drPerformance.Rank = 0;
                        drPerformance.SecondaryRank = 0;
                        drPerformance.Reaction = string.Empty;
                        drPerformance.Points = 0;
                        drPerformance.PointsScoring = true;
                        drPerformance.Active = true;
                        drPerformance.Sync = false;
                        drPerformance.WebId = 0;
                        drPerformance.Modified = DateTime.Now;
                        drPerformance.SetRealStartTimeNull();

                        this.aDbDataSet.Performances.AddPerformancesRow(drPerformance);

                        dgvr.Cells["chk"].Value = false;
                    }
                }

                // Save
                this.taPerformances.Update(this.aDbDataSet.Performances);

                // Reload
                this.ReloadPerformancesGrid();
            }
            catch (Exception ex)
            {
                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        // Delete entries
        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                int count = 0;

                if (MessageBox.Show("Naozaj chcete odhlásiť označených pretekárov?", "Prihlášky", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    for (int i = dgvPerformances.Rows.Count - 1; i >= 0; i--)
                    {
                        DataGridViewRow dgvr = dgvPerformances.Rows[i];

                        if (Convert.ToBoolean(dgvr.Cells["chkDel"].Value))
                        {
                            DataRow drPerformance = ((DataRowView)dgvr.DataBoundItem).Row;
                            // drPerformance.Delete();
                            drPerformance["Active"] = false;
                            this.taPerformances.Update(drPerformance);
                            count += 1;
                        }
                    }
                }

                if (count > 0)
                    MessageBox.Show("Pretekári boli odhlásení." + Environment.NewLine + "Počet: " + count.ToString(),
                        "Prihlášky", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Záznamy nie je možné vymazať, pretože sa používajú." + Environment.NewLine + ex.Message, "Prihlášky", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            this.ReloadPerformancesGrid();
        }

        #endregion


    }
}
